package cn.com.callback;

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.DateFormat
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONObject;

//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.parser.Feature;

import org.json.JSONArray;
import org.json.JSONException;
import cn.com.elite.Util;
import cn.com.kh.KHUtil;
import cn.com.kh.signUtil;
import cn.com.kh.AESUtil;

/**
 *
 * @Title: ApiBPRegister
 * @Description:深圳宝安排水系统工单录入同步接口--内部接口
 * 根据openid和手机号码，在客服系统内注册客户
 * @author: chieh
 * @date 2020-11-11 21:28:00
 *
 */

public class ApiBPRegister implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ApiBPRegister.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        //response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }
        long startTime = System.currentTimeMillis();

        String reJson = null;
        long endTime = 0;
        String dealMessage = "";

        JSONArray resArray = new JSONArray();
        JSONObject resObject = new JSONObject();

        try {

            // 调用处理信息
            //JSONObject inObject = JSONObject.parseObject(inData, Feature.OrderedField);
            JSONObject inObject = new JSONObject(inData);
            log.debug("处理前的Json：" + inObject.toString());

            //openid  mobile customername 排序问题
            JSONArray jsonArraytemp = new JSONArray(inObject.get("data").toString());
            log.debug("jsonArraytemp: " + jsonArraytemp);

            JSONObject dataObjecttemp = jsonArraytemp.getJSONObject(0);
            log.debug(dataObjecttemp);
            String openidtemp = GetJV(dataObjecttemp, "openid");
            String mobiletemp = GetJV(dataObjecttemp, "mobile");
            String customernametemp = GetJV(dataObjecttemp, "customername");
            log.debug("openid:" + openidtemp + "	,mobile:" + mobiletemp + "	,customername:" + customernametemp);

            String replaceString = "[{\"openid\":\"" + openidtemp + "\",\"mobile\":\"" + mobiletemp + "\",\"customername\":\"" + customernametemp + "\"}]";
            log.debug("replaceString:" + replaceString);

            //鉴权加密处理--验证密码
            JSONObject checkJson = signUtil.CheckSign(inObject, replaceString);
            log.debug("checkJson: " + checkJson);

            if (checkJson != null) {
                log.debug("[签名校验异常-返回信息]:" + checkJson);
                endTime = System.currentTimeMillis();
                reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败([签名校验异常-返回信息]:" + signUtil.jsonObjectToMap(checkJson) + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;
            } else {
                log.debug("[签名校验成功]");
                // 校验成功
                //todo 业务逻辑
            }

            //data 获取参数openid
            JSONArray jsonArray = new JSONArray(inObject.get("data").toString());
            log.debug("jsonArray: " + jsonArray);
            String openid = jsonArray.getJSONObject(0).get("openid");//openid
            String customername = jsonArray.getJSONObject(0).get("customername");//联系人
            String mobile = jsonArray.getJSONObject(0).get("mobile");//电话号码

            log.debug("解析信息-openid：" + openid + " customername：" + customername + " mobile：" + mobile);

            //必填项校验
            if (isNull(openid) || isNull(customername) || isNull(mobile)) {
                dealMessage = isNullMSG("openid", openid) + isNullMSG("customername", customername) + isNullMSG("mobile", mobile);
                endTime = System.currentTimeMillis();
                log.warn(dealMessage);
                reJson = "{\"result\":\"0\",\"resultmessage\":\"处理失败(" + dealMessage + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;
            } else {

                // 检查是否是有效OpenID
                JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
                String selectSQL = "Select  top 1 Rec_Id, Js_Code, Open_Id, Unionid, Session_Key, Errcode, Errmsg From Kh_Minip_Login Where Open_Id = ? Order By Createdtime Desc";
                List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, openid);
                log.debug("检查是否是有效OpenID:" + selectExits);

                if (selectExits.size() > 0) {
                    //处理客户
                    def customerresult = eliteBean.chaxun_sql("select  top 1 wechatid as wechatid,customername as customername,mobile as mobile from CUSTOMER  where wechatid='" + openid + "' ORDER BY CREATEDDATE asc", "dataSource");
                    log.debug("查看客户是否存在sql结果:" + customerresult);

                    String wechatid1 = null;
                    String customername1 = null;
                    String mobile1 = null;
                    if (customerresult.size() > 0) {
                        wechatid1 = customerresult.get(0).get("wechatid");
                        customername1 = customerresult.get(0).get("customername");
                        mobile1 = customerresult.get(0).get("mobile");

                        resObject.put("openid", wechatid1);
                        resObject.put("customername", customername1);
                        resObject.put("mobile", mobile1);

                        resArray.put(resObject);

                        endTime = System.currentTimeMillis();
                        outData = "{\"resultcode\":\"2\",\"resultmessage\":\"该用户已注册，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray + "}";
                    } else {
                        //生成随机36位id
                        String Relation_ID = UUID.randomUUID().toString();
                        log.debug("customer_guid:" + Relation_ID);
                        eliteBean.update("insert into CUSTOMER (CUSTOMER_GUID,CUSTOMERNAME,MOBILE,wechatid,CREATEDBY,CREATEDDATE,customertype2_id) values('" + Relation_ID + "','" + customername + "','" + mobile + "','" + openid + "','SELITE',GETDATE(),'000001')", dataSourceID);

                        resObject.put("openid", openid);
                        resObject.put("customername", customername);
                        resObject.put("mobile", mobile);

                        resArray.put(resObject);

                        endTime = System.currentTimeMillis();
                        outData = "{\"resultcode\":\"1\",\"resultmessage\":\"注册成功，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray + "}";
                    }
                } else {

                    endTime = System.currentTimeMillis();
                    reJson = "{\"result\":\"0\",\"resultmessage\":\"处理失败:无效的OpenID,调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    return reJson;

                }
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\"}";

        }
        return outData;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        return Rev_Value;
    }

    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}